//
//  YCNetworkManager.m
//  DemoWiFi
//
//  Created by tangkexiong on 16/4/13.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCNetworkManager.h"

#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import <dlfcn.h>
#import <SystemConfiguration/CaptiveNetwork.h>

@implementation YCNetworkManager

+ (NSString *)getIPAddress {
    NSString *localIP = nil;
    
    struct ifaddrs *addrs;
    
    if (getifaddrs(&addrs)==0) {
        
        const struct ifaddrs *cursor = addrs;
        
        while (cursor != NULL) {
            
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
                
            {
                
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                
                if ([name isEqualToString:@"en0"]) // Wi-Fi adapter
                    
                {
                    
                    localIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
                    
                    break;
                    
                }
                
            }  
            
            cursor = cursor->ifa_next;  
            
        }  
        
        freeifaddrs(addrs);  
        
    }  
    
    return localIP;
}

+ (NSString *)getWifiName {
    NSString *wifiName = nil;
    
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        return nil;
    }
    
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            
            CFRelease(dictRef);
        }
    }
    
    CFRelease(wifiInterfaces);
    return wifiName;
}

@end
